﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Networking.Connectivity;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace Weather
{
    public sealed partial class Day1Weather : UserControl
    {
        public HttpClient httpClient;
        Weather.Data.Weather w = null;
        //string city = "北京";
        static string inputString;

        

        public static DependencyProperty InputControlProperty = DependencyProperty.Register(
            "City",
            typeof(string),
            typeof(Day1Weather),
            new PropertyMetadata("",OnCityChanged));

        private static  void OnCityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (e.Property == InputControlProperty)
            {
                inputString = (string)e.NewValue;
                
            }
            
            Debug.WriteLine("输出InputString2:" + inputString);
          
        }
        public string City
        {
            get
            {
                return ((string)base.GetValue(InputControlProperty));
            }
            set
            {
                base.SetValue(InputControlProperty, value);
                if (OnLoadChanged != null)
                {
                    OnLoadChanged(this, new EventArgs());
                }
            }
        }

        public static DependencyProperty DayProperty = DependencyProperty.Register(
           "Day",
           typeof(int),
           typeof(Day1Weather),
           null);
        public  int Day
        {
            get
            {
                return ((int)base.GetValue(DayProperty));
            }
            set
            {
                base.SetValue(DayProperty, value);
            }
        }
        public string dataPackageTitle { get; set; }
        public string dataPackageDescription { get; set; }
        public string  dataPackageText { get; set; }

         //this.dataPackageTitle = w.city + "天气预报";
         //this.dataPackageDescription = "看天气，了解最近天气预报";
         //this.dataPackageText = w.city + "\n" + w.temperature1 + "-" + w.temperature2 + "\n" + w.savedate_weather;



        public event EventHandler OnLoadChanged;

      
        public Day1Weather()
        {
            this.InitializeComponent();
            this.Loaded += Day1Weather_Loaded;
            

        }

        private async  void Day1Weather_Loaded(object sender, RoutedEventArgs e)
        {
            inputString = City;
            Debug.WriteLine("输出InputString1:" + inputString);
           await GetWeatherByDays(City, Day);
           
        }

        private  async Task GetWeatherByDays(string city,int i)
        {
            Debug.WriteLine("输出InputString2:" + city);
            city = UTF8ToGB2312(city);
            string uri = "http://php.weather.sina.com.cn/xml.php?city=" + city + "&password=DJOYnieT8234jlsK&day=" + i + "";
            CreateClient(new Uri(uri));
            await GetWeather();
        }

        private async Task GetWeather()
        {
            try
            {
                HttpResponseMessage response = await httpClient.GetAsync("");

                XElement element = XElement.Parse(await response.Content.ReadAsStringAsync());

                w = new Weather.Data.Weather();
                #region foreach 读取xml数据

                foreach (XElement xml in element.Descendants("Weather"))
                {

                    //TODO 判断城市
                    w.city = xml.Element("city").Value;

                    w.status1 = xml.Element("status1").Value;
                    w.status2 = xml.Element("status2").Value;
                    w.figure1 = string.Format("http://php.weather.sina.com.cn/images/yb3/78_78/{0}_0.png", xml.Element("figure1").Value);
                    w.figure2 = string.Format("http://php.weather.sina.com.cn/images/yb3/78_78/{0}_1.png", xml.Element("figure2").Value);
                    w.direction1 = xml.Element("direction1").Value;
                    w.direction2 = xml.Element("direction2").Value;
                    w.power1 = xml.Element("power1").Value;
                    w.power2 = xml.Element("power2").Value;
                    w.temperature1 = xml.Element("temperature1").Value;
                    w.temperature2 = xml.Element("temperature2").Value;
                    w.ssd = xml.Element("ssd").Value;
                    w.tgd1 = xml.Element("tgd1").Value;
                    w.tgd2 = xml.Element("tgd2").Value;
                    w.zwx = xml.Element("zwx").Value;
                    w.ktk = xml.Element("ktk").Value;
                    w.pollution = xml.Element("pollution").Value;
                    w.xcz = xml.Element("xcz").Value;
                    w.zho = xml.Element("zho").Value;
                    w.diy = xml.Element("diy").Value;
                    w.fas = xml.Element("fas").Value;
                    w.chy = xml.Element("chy").Value;
                    w.zho_shuoming = xml.Element("zho_shuoming").Value;
                    w.diy_shuoming = xml.Element("diy_shuoming").Value;
                    w.fas_shuoming = xml.Element("fas_shuoming").Value;
                    w.chy_shuoming = xml.Element("chy_shuoming").Value;
                    w.pollution_l = xml.Element("pollution_l").Value;
                    w.zwx_l = xml.Element("zwx_l").Value;
                    w.ssd_l = xml.Element("ssd_l").Value;
                    w.fas_l = xml.Element("fas_l").Value;
                    w.zho_l = xml.Element("zho_l").Value;
                    w.chy_l = xml.Element("chy_l").Value;
                    w.ktk_l = xml.Element("ktk_l").Value;
                    w.xcz_l = xml.Element("xcz_l").Value;
                    w.diy_l = xml.Element("diy_l").Value;
                    w.pollution_s = xml.Element("pollution_s").Value;
                    w.zwx_s = xml.Element("zwx_s").Value;
                    w.ssd_s = xml.Element("ssd_s").Value;
                    w.ktk_s = xml.Element("ktk_s").Value;
                    w.xcz_s = xml.Element("xcz_s").Value;
                    w.gm = xml.Element("gm").Value;
                    w.gm_l = xml.Element("gm_l").Value;
                    w.gm_s = xml.Element("gm_s").Value;
                    w.yd = xml.Element("yd").Value;
                    w.yd_l = xml.Element("yd_l").Value;
                    w.yd_s = xml.Element("yd_s").Value;
                    w.savedate_weather = xml.Element("savedate_weather").Value;
                    w.savedate_life = xml.Element("savedate_life").Value;
                    w.savedate_zhishu = xml.Element("savedate_zhishu").Value;
                }

                #endregion

                //显示数据
                DisplayDataWeather();
                //DisplayDataWeather1();
                DisplayIndex();
                // DisplayIndex1();
                
                this.dataPackageTitle = w.city + "天气预报";
                this.dataPackageDescription = "看天气，了解最近天气预报";
                this.dataPackageText = w.city + "\n" + w.temperature1 + "-" + w.temperature2 + "\n" + w.savedate_weather;
                (Application.Current as App).weather = w;

            }
            catch (HttpRequestException hre)
            { }
            catch (Exception ex)
            { }
        }

        private void DisplayIndex()
        {
            indexChy.Index = "穿衣指数:" + w.chy_l;
            indexChy.IndexContext = w.chy_shuoming;
            indexChy.IndexImage = new BitmapImage(new Uri("ms-appx:///Images/chuanyi.png"));
            indexGm.Index = "感冒指数:" + w.gm_l;
            indexGm.IndexContext = w.gm_s;
            indexGm.IndexImage = new BitmapImage(new Uri("ms-appx:///Images/ganmao.png"));
            indexKtk.Index = "空调指数:" + w.ktk_l;
            indexKtk.IndexContext = w.ktk_s;
            indexKtk.IndexImage = new BitmapImage(new Uri("ms-appx:///Images/kongtiao.png"));
            indexPollution.Index = "污扩散条件:" + w.pollution_l;
            indexPollution.IndexContext = w.pollution_s;
            indexPollution.IndexImage = new BitmapImage(new Uri("ms-appx:///Images/wuran.png"));
            indexSsd.Index = "体感指数:" + w.ssd_l;
            indexSsd.IndexContext = w.ssd_s;
            indexSsd.IndexImage = new BitmapImage(new Uri("ms-appx:///Images/tiganwendu.png"));
            indexXcz.Index = "洗车指数:" + w.xcz_l;
            indexXcz.IndexContext = w.xcz_s;
            indexXcz.IndexImage = new BitmapImage(new Uri("ms-appx:///Images/xiche.png"));
            indexYd.Index = "运动指数:" + w.yd_l;
            indexYd.IndexContext = w.yd_s;
            indexYd.IndexImage = new BitmapImage(new Uri("ms-appx:///Images/yundong.png"));
            indexZwx.Index = "紫外线指数:" + w.zwx_l;
            indexZwx.IndexContext = w.zwx_s;
            indexZwx.IndexImage = new BitmapImage(new Uri("ms-appx:///Images/ziwaixian.png"));
            UserControlIndex ucIndex = new UserControlIndex();
        }

        private void DisplayDataWeather()
        {
            //pageTitle.Text = w.city;
            userControlWeather.Status1 = w.status1;
            userControlWeather.Status2 = w.status2;
            userControlWeather.WeatherWhiteIcon = new BitmapImage(new Uri(w.figure1));
            userControlWeather.WeatherNightIcon = new BitmapImage(new Uri(w.figure2));
            userControlWeather.DateTime = w.savedate_weather + "  " + DateTime.Now.ToString("dddd", new System.Globalization.CultureInfo("zh-cn"));// DateTime.Now.DayOfWeek.ToString();
            //w.savedate_weather;
            userControlWeather.Temperature1 = string.Format("{0}℃", w.temperature1);
            userControlWeather.Tgd1 = string.Format("{0}℃", w.tgd1);
            userControlWeather.Temperature2 = string.Format("{0}℃", w.temperature2);
            userControlWeather.Power1 = w.power1;
            userControlWeather.Power2 = w.power2;
            userControlWeather.Direction1 = w.direction1;
            userControlWeather.Direction2 = w.direction2;
        }

        private void CreateClient(Uri server)
        {
            if (httpClient != null)
            {
                httpClient.Dispose();
            }
            HttpMessageHandler handler = new HttpClientHandler();
            handler = new PlugInHandler(handler);
            httpClient = new HttpClient(handler);
            httpClient.BaseAddress = server;
            httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Sample", "v8"));
        }

        private string UTF8ToGB2312(string str)
        {
            try
            {
                Encoding gb2312 = Encoding.GetEncoding("gb2312");
                byte[] buffer = gb2312.GetBytes(str);
                StringWriter sw = new StringWriter();
                for (int i = 0; i < buffer.Length; i++)
                {
                    sw.Write("%" + buffer[i].ToString("X2"));
                }
                return sw.ToString();
            }
            catch (Exception ex)
            {
                //MessageDialog meg = new MessageDialog(ex.ToString(),"转换错误");
                return null;
            }
        }

       //async void btnAdd_Click(object sender, RoutedEventArgs e)
       // {
       //     PopupInputControl inputDialog = new PopupInputControl();
       //     Popup popup = new Popup
       //     {
       //         Child = inputDialog,
       //         IsLightDismissEnabled = true
       //     };
       //     inputDialog.OnValueChanged += (dialogSender, dialogArgs) =>
       //     {
       //         Debug.WriteLine("输出inputDialog.InputString：" + inputDialog.InputString);

       //         City = inputDialog.InputString;

       //         popup.IsOpen = false;
       //         if (!string.IsNullOrEmpty(City))
       //         {
       //            GetWeatherByDays(Day);
       //         }
       //     };
       //     inputDialog.SizeChanged += (dialogSender, dialogArgs) =>
       //     {
       //         popup.VerticalOffset = this.ActualHeight - inputDialog.ActualHeight  - 100;
       //         popup.HorizontalOffset = this.ActualWidth - 400;
       //     };
       //     popup.IsOpen = true;

       // }
    }
}
